package com.seventh.restaurant.service.Impl;

import com.seventh.restaurant.domain.Table;
import com.seventh.restaurant.repository.TableRepository;
import com.seventh.restaurant.service.TableService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TableServiceImpl implements TableService {

    private final TableRepository tableRepository;

    public TableServiceImpl(TableRepository tableRepository) {
        this.tableRepository = tableRepository;
    }

    @Override
    public List<Table> findAllValidTables() {
        return tableRepository.findValidTables();
    }

    @Override
    public Table insertTable(Table table) throws Exception {
        Table table1 = tableRepository.findByTableNo(table.getTableNo());
        if (table1!=null){
            Table table2 = new Table();
            table2.setTableNo("该餐桌已经存在,不可重复添加");
            return  table2;
        }else {
            table.setIsBusy("0");
            table.setIsRecord("0");
            return tableRepository.save(table);
        }
    }

    @Override
    public void deleteTable(Long id) {

        tableRepository.delete(id);

    }

    @Override
    public Table updateTable(Table table) throws Exception {
        Table table1 = tableRepository.findByTableNo(table.getTableNo());
        if (table1==null){
            throw new Exception("该餐桌不存在,请先添加编号为"+table.getTableNo()+"的餐桌信息");
        }else {
            table1.setSize(table.getSize());
            table1.setIsBusy(table.getIsBusy());
            table1.setIsRecord(table.getIsRecord());
            table1 = tableRepository.save(table1);
            if (table1.getId()<=0){
                throw new Exception("餐桌信息修改不成功");
            }else {
                return table1;
            }
        }
    }

    @Override
    public Table findTable(String tableNo) {
        return tableRepository.findByTableNo(tableNo);
    }

    @Override
    public List<Table> findAllTables() {
        return tableRepository.findAll();
    }

    @Override
    public List<Table> findValidTables(String peoplenum) {
        return tableRepository.findTablesByPeopleNum(peoplenum);
    }
}
